//
//  TextViewController.swift
//  约麻
//
//  Created by Syrena on 2017/7/17.
//  Copyright © 2017年 Sweet. All rights reserved.
//

import UIKit

class TextViewController: UIViewController {
    
    var mapview=BMKMapView()
    var locationserivce=BMKLocationService()
    var mapPin:UIButton?
    var geocode=BMKGeoCodeSearch()
    var long:Double?
    var lat:Double?
    var searchPOI=BMKPoiSearch()
    var searchLBS=BMKCloudSearch()

    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        mapview.delegate = self
        locationserivce.delegate = self
        geocode.delegate = self
        searchPOI.delegate = self
        // Do any additional setup after loading the view.
        
        mapview.isZoomEnabled = true
        //mapview.zoomLevel = 21
        mapview.frame = view.bounds
        
        //启动LocationService
        locationserivce.startUserLocationService()
        mapview.showsUserLocation = false
        //设置位置跟踪态
        mapview.userTrackingMode = BMKUserTrackingModeFollow
        //显示定位图层
        mapview.showsUserLocation = true
        
        
        
        view.addSubview(mapview)
        // 设置定位精确度，默认：kCLLocationAccuracyBest
        //BMKLocationService.setLocationDesiredAccuracy(kCLLocationAccuracyBest)
        locationserivce.desiredAccuracy = kCLLocationAccuracyBest
        
        //指定最小距离更新(米)，默认：kCLDistanceFilterNone
        //BMKLocationService.setLocationDistanceFilter(10)
        locationserivce.distanceFilter = 10
        
        //初始化BMKLocationService
        //locationserivce = BMKLocationService()
        
        
        

    }
        
        //搜索
        func searchpoi(){
            /*//初始化检索对象
             _searcher =[[BMKPoiSearch alloc]init];
             _searcher.delegate = self;
             //发起检索
             BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
             option.pageIndex = curPage;
             option.pageCapacity = 10;
             option.location = CLLocationCoordinate2D{39.915, 116.404};
             option.keyword = @"小吃";
             BOOL flag = [_searcher poiSearchNearBy:option];
             [option release];*/
            let option = BMKNearbySearchOption()
            //option.pageIndex = 2
            option.pageCapacity = 1;
            option.location = CLLocationCoordinate2DMake(lat!, long!)
            option.keyword = "茶楼"
            
            let op = BMKPoiDetailSearchOption()
            op.poiUid = "b9b8bff64d28b5bc38e4a6fc"
            //searchPOI.poiSearchNear(by: option)
            searchPOI.poiDetailSearch(op)
        }
        func outputAdd(){
            let option = BMKReverseGeoCodeOption()
            option.reverseGeoPoint = CLLocationCoordinate2DMake(lat!, long!)
            print(option.reverseGeoPoint.latitude)
            geocode.reverseGeoCode(option)
        }
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */



extension TextViewController:BMKMapViewDelegate{
    func mapView(_ mapView: BMKMapView!, regionDidChangeAnimated animated: Bool) {
        // let MapCoordinate = mapview.convert(mapview.center, toCoordinateFrom: mapview)
        
        /*//屏幕坐标转地图经纬度
         CLLocationCoordinate2D MapCoordinate=[_mapView convertPoint:_mapPin.center toCoordinateFromView:_mapView];
         NSLog(@"latitude == %f longitude == %f",MapCoordinate.latitude,MapCoordinate.longitude);
         if (_geoCodeSearch==nil) {
         //初始化地理编码类
         _geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
         _geoCodeSearch.delegate = self;
         
         }
         if (_reverseGeoCodeOption==nil) {
         
         //初始化反地理编码类
         _reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
         }
         //需要逆地理编码的坐标位置
         _reverseGeoCodeOption.reverseGeoPoint =MapCoordinate;
         [_geoCodeSearch reverseGeoCode:_reverseGeoCodeOption];
         
         //创建地理编码对象
         CLGeocoder *geocoder=[[CLGeocoder alloc]init];
         //创建位置
         CLLocation *location=[[CLLocation alloc]initWithLatitude:MapCoordinate.latitude longitude:MapCoordinate.longitude];
         
         //反地理编码
         [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
         //判断是否有错误或者placemarks是否为空
         if (error !=nil || placemarks.count==0) {
         NSLog(@"%@",error);
         return ;
         }
         for (CLPlacemark *placemark in placemarks) {
         //赋值详细地址
         NSLog(@"%@",placemark.name);
         }
         }]; */
    }
    
    /*//#pragma mark 获取地理位置按钮事件
     - (void)outputAdd
     {
     // 初始化反地址编码选项（数据模型）
     BMKReverseGeoCodeOption *option = [[BMKReverseGeoCodeOption alloc] init];
     // 将数据传到反地址编码模型
     option.reverseGeoPoint = CLLocationCoordinate2DMake(self.latitude, self.longitude);
     NSLog(@"%f - %f", option.reverseGeoPoint.latitude, option.reverseGeoPoint.longitude);
     // 调用反地址编码方法，让其在代理方法中输出
     [self.geoCode reverseGeoCode:option];
     }*/
    
    
}

extension TextViewController:BMKLocationServiceDelegate{
    func didUpdateUserHeading(_ userLocation: BMKUserLocation!) {
        mapview.showsUserLocation = true
        
        mapview.updateLocationData(userLocation)
        
        /*BMKCoordinateRegion region ;//表示范围的结构体
         region.center = self.mapView.centerCoordinate;//中心点
         region.span.latitudeDelta = 0.004;//经度范围（设置为0.1表示显示范围为0.2的纬度范围）
         region.span.longitudeDelta = 0.004;//纬度范围
         [self.mapView setRegion:region animated:YES]; */
        
        
    }
    
    func didUpdate(_ userLocation: BMKUserLocation!) {
        lat = userLocation.location.coordinate.latitude
        long = userLocation.location.coordinate.longitude
        mapview.updateLocationData(userLocation)
        
        print(lat ?? 0,long ?? 0)
        var region = BMKCoordinateRegion()
        region.center = mapview.centerCoordinate
        region.span.latitudeDelta = 0.1
        region.span.longitudeDelta = 0.1
        
        mapview.setRegion(region, animated: true)
    }
    
    
}

extension TextViewController:BMKGeoCodeSearchDelegate{
    //反编码
    func onGetGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
        mapview.removeAnnotations(mapview.annotations)
        if error == BMK_SEARCH_NO_ERROR {
            let item = BMKPointAnnotation()
            item.coordinate = result.location
            item.title = result.address
            mapview.addAnnotation(item)
            mapview.centerCoordinate = result.location
            
            let showMessage = "纬度:\(item.coordinate.latitude)，经度:\(item.coordinate.longitude)"
            
            let alertView = UIAlertController(title: "正向地理编码", message: showMessage, preferredStyle: .alert)
            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alertView.addAction(okAction)
            self.present(alertView, animated: true, completion: nil)
        }
    }
    
    //编码
    func onGetReverseGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
        if error == BMK_SEARCH_NO_ERROR {
            let item = BMKPointAnnotation()
            item.coordinate = result.location
            item.title = result.address
            mapview.addAnnotation(item)
            mapview.centerCoordinate = result.location
            
            let alertView = UIAlertController(title: "反向地理编码", message: result.address, preferredStyle: .alert)
            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alertView.addAction(okAction)
            self.present(alertView, animated: true, completion: nil)
        }
        
    }
}

extension TextViewController:BMKPoiSearchDelegate{
    func onGetPoiResult(_ searcher: BMKPoiSearch!, result poiResult: BMKPoiResult!, errorCode: BMKSearchErrorCode) {
        if errorCode == BMK_SEARCH_NO_ERROR{
            let arrayM = poiResult.poiInfoList as? [BMKPoiInfo]
            for model in arrayM! {
                print(model.uid,model.name,model.address)
            }
            
        }
        else if errorCode == BMK_SEARCH_AMBIGUOUS_KEYWORD{
            //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
            // result.cityList;
            print("起始点有歧义");
        } else {
            print("抱歉，未找到结果");
        }
        
    }
    func onGetPoiDetailResult(_ searcher: BMKPoiSearch!, result poiDetailResult: BMKPoiDetailResult!, errorCode: BMKSearchErrorCode) {
        if errorCode == BMK_SEARCH_NO_ERROR{
            print(poiDetailResult.debugDescription,poiDetailResult.description,poiDetailResult.price)
            
        }
    }
}


